package chen.huai.jie.spring.xmlconfig.mq.activemq.sender;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.TextMessage;
import java.util.UUID;

@Service
public class ActiveMqSender {
    private Logger logger = LoggerFactory.getLogger(ActiveMqSender.class);

    @Autowired(required = false)
    private JmsTemplate jmsTemplateForQueue;

    @Autowired(required = false)
    private JmsTemplate jmsTemplateForTopic;

    public void sendMessageToQueue(ActiveMQQueue queue, final String message) {
        try {
            jmsTemplateForQueue.send(queue, session -> {
                TextMessage textMessage = session.createTextMessage(message);
                textMessage.setJMSMessageID(UUID.randomUUID().toString());
                return textMessage;
            });


            logger.info(String.format("Send message to %s successfully.", queue.getQueueName()));
        } catch (Exception e) {
            logger.error(String.format("Failed to send message to %s.", queue));
        }

    }

    public void sendMessageToTopic(ActiveMQTopic topic, final String message) {
        try {
            jmsTemplateForTopic.send(topic, session -> session.createTextMessage(message));
            logger.info(String.format("Send message to %s successfully.", topic.getTopicName()));
        } catch (Exception e) {
            logger.error(String.format("Failed to send message to %s.", topic));
        }
    }
}
